package routing.googleadapter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.android.gms.maps.model.LatLng;


/**
 * Gets a route between two coords from Google
 * 
 * @author Alexander Münch (sialmuen)
 */
public class GoogleReverseGeocoderAdapter {
	private static final long serialVersionUID = 1L;
	
	static Logger logger = Logger.getLogger(GoogleRoutingAdapter.class.toString());

     /* gets the route. This method may be called be other services!
     * 
     * @param from
     * @param to
     * @return String KML data
     */
	
    public static String getGooglePositionAsKML(LatLng position) {
    	String response = null;
    	String url = getURL(position);
    	response = queryWebpage(url);

    	System.out.println("REVERSE: " + response);
    	return response;
    }
    
    private static String queryWebpage(String targetURL) {
    	return queryWebpage(targetURL, false);
    }
    
    /**
	 * calls the requested URL and returns its source
	 * @param zielUrl URL die aufgerufen werden soll
	 * @param mitNewlines true wenn newlines mitgelesen werden sollen, sonst false
	 * @return
	 */
    // FIXME: copied from BahnRoute2.java - duplicate code
	private static String queryWebpage(String targetURL, boolean mitNewlines){
		// logger.log(Level.INFO, "Requesting URL: " + targetURL.toString());
		String xml = null;
		StringBuffer content = new StringBuffer();

		try {
			URL url = new URL(targetURL.toString());
			URLConnection uc = url.openConnection();
			BufferedReader googleIn = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
			String b;
			
			while ((b = googleIn.readLine()) != null) {
				/*
				content.append(inputLine);
				if (mitNewlines) content.append("\n");
				*/
				
				content.append(b.trim());
			}
			
			xml = content.toString();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//logger.log(Level.INFO,"Response: " + xml);
		//System.out.println("Response: " + xml);
		return xml;
	}
    
    /**
     * returns a URL for querying Google for a route
     * example: http://maps.google.com/maps?oe=UTF-8&output=kml&saddr=Nürnberg Hauptbahnhof&daddr=Nürnberg Flughafen&dirflg=w
     * 
     * @see http://mapki.com/wiki/Google_Map_Parameters
     * 
     * @param from
     * @param to
     * @return URL
     */
    private static String getURL(LatLng position) {
    	String url = "http://maps.googleapis.com/maps/api/geocode/xml?";
    	url += "latlng=" + position.latitude + "," + position.longitude;
    	url += "&sensor=false";
    	
    	logger.log(Level.INFO, url);
    	return url;
    }

	protected void doGet(LatLng position) {
		// ask Google for the route and convert it to JSON
		String kmlRoute = getGooglePositionAsKML(position);
		GoogleKMLParser kmlParser = new GoogleKMLParser(kmlRoute);
		String waypointsArray = kmlParser.toJSON();
		
		String output = new String("{\"status\":\"OK\", \"data\":[ \"waypoints\": " + waypointsArray + "]}");
		System.out.println(output);
	}
}
